package com.example.user.service.login.impl;

import cn.hutool.core.lang.Assert;
import com.example.framework.common.util.json.JsonUtils;
import com.example.framework.security.core.LoginUser;
import com.example.framework.security.core.dto.JwtTokenRespDto;
import com.example.framework.security.core.util.JwtTokenUtils;
import com.example.user.constants.LoginTypeEnum;
import com.example.user.constants.SourceTypeEnum;
import com.example.user.controller.auth.vo.LoginReqVO;
import com.example.user.service.code.CodeService;
import com.example.user.service.code.CodeServiceFactory;
import com.example.user.service.login.LoginService;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

@Service
public class CodeLoginServiceImpl implements LoginService {

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Resource
    private CodeServiceFactory codeServiceFactory;

    @Override
    public JwtTokenRespDto login(LoginReqVO loginReqVO) {
        String code = loginReqVO.getCode();
        Assert.notBlank(code, "验证码不能为空");

        Integer source = loginReqVO.getSource();
        String loginId = loginReqVO.getId();
        // 先校验验证码
        verifyCode(source, loginId, code);

        LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(JsonUtils.toJsonString(loginReqVO));
        return jwtTokenUtils.generateTokenAndRefreshToken(loginUser);
    }

    private void verifyCode(int source, String loginId, String code) {
        CodeService codeService = codeServiceFactory.get(SourceTypeEnum.get(source));
        codeService.verifyCode(loginId, code, true);
    }

    @Override
    public LoginTypeEnum getType() {
        return LoginTypeEnum.BY_CODE;
    }
}
